<template>
  <div class="pivot-report">
    <!-- 页面标题和操作栏 -->
    <div class="report-header">
      <h2>数据透视报表</h2>
      <div class="header-actions">
        <el-button type="primary" @click="showConfigDialog = true">
          <el-icon><Setting /></el-icon>
          配置透视表
        </el-button>
        <el-button @click="saveConfig">
          <el-icon><DocumentAdd /></el-icon>
          保存配置
        </el-button>
        <el-button @click="loadConfig">
          <el-icon><FolderOpened /></el-icon>
          加载配置
        </el-button>
        <el-dropdown style="margin-left: 10px;">
          <el-button type="success">
            导出 <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="exportExcel">导出Excel</el-dropdown-item>
              <el-dropdown-item @click="exportPDF">导出PDF</el-dropdown-item>
              <el-dropdown-item @click="exportImage">导出图片</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <el-button @click="printReport" style="margin-left: 10px;">
          <el-icon><Printer /></el-icon>
          打印
        </el-button>
      </div>
    </div>

    <!-- 透视表配置区域 -->
    <el-row :gutter="20" class="config-section">
      <el-col :span="6">
        <el-card>
          <template #header>
            <span>可用字段</span>
          </template>
          <div class="field-list">
            <div 
              v-for="field in availableFields" 
              :key="field.key"
              class="field-item"
              draggable="true"
              @dragstart="handleDragStart($event, field)"
            >
              <el-icon><Grid /></el-icon>
              {{ field.label }}
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="18">
        <el-row :gutter="10">
          <!-- 行字段 -->
          <el-col :span="12">
            <el-card class="drop-zone">
              <template #header>
                <span>行字段</span>
              </template>
              <div 
                class="drop-area"
                @drop="handleDrop($event, 'rows')"
                @dragover="handleDragOver"
              >
                <div 
                  v-for="(field, index) in rowFields" 
                  :key="field.key"
                  class="field-tag"
                >
                  <el-tag closable @close="removeField('rows', index)">
                    {{ field.label }}
                  </el-tag>
                </div>
                <div v-if="rowFields.length === 0" class="drop-placeholder">
                  拖拽字段到此处作为行
                </div>
              </div>
            </el-card>
          </el-col>
          
          <!-- 列字段 -->
          <el-col :span="12">
            <el-card class="drop-zone">
              <template #header>
                <span>列字段</span>
              </template>
              <div 
                class="drop-area"
                @drop="handleDrop($event, 'columns')"
                @dragover="handleDragOver"
              >
                <div 
                  v-for="(field, index) in columnFields" 
                  :key="field.key"
                  class="field-tag"
                >
                  <el-tag closable @close="removeField('columns', index)">
                    {{ field.label }}
                  </el-tag>
                </div>
                <div v-if="columnFields.length === 0" class="drop-placeholder">
                  拖拽字段到此处作为列
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
        
        <el-row :gutter="10" style="margin-top: 10px;">
          <!-- 数值字段 -->
          <el-col :span="12">
            <el-card class="drop-zone">
              <template #header>
                <span>数值字段</span>
              </template>
              <div 
                class="drop-area"
                @drop="handleDrop($event, 'values')"
                @dragover="handleDragOver"
              >
                <div 
                  v-for="(field, index) in valueFields" 
                  :key="field.key"
                  class="field-tag"
                >
                  <el-tag closable @close="removeField('values', index)">
                    {{ field.label }} ({{ field.aggregation }})
                    <el-dropdown trigger="click" style="margin-left: 5px;">
                      <el-icon><ArrowDown /></el-icon>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <el-dropdown-item @click="changeAggregation(index, 'sum')">求和</el-dropdown-item>
                          <el-dropdown-item @click="changeAggregation(index, 'avg')">平均值</el-dropdown-item>
                          <el-dropdown-item @click="changeAggregation(index, 'count')">计数</el-dropdown-item>
                          <el-dropdown-item @click="changeAggregation(index, 'max')">最大值</el-dropdown-item>
                          <el-dropdown-item @click="changeAggregation(index, 'min')">最小值</el-dropdown-item>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </el-tag>
                </div>
                <div v-if="valueFields.length === 0" class="drop-placeholder">
                  拖拽数值字段到此处
                </div>
              </div>
            </el-card>
          </el-col>
          
          <!-- 筛选字段 -->
          <el-col :span="12">
            <el-card class="drop-zone">
              <template #header>
                <span>筛选字段</span>
              </template>
              <div 
                class="drop-area"
                @drop="handleDrop($event, 'filters')"
                @dragover="handleDragOver"
              >
                <div 
                  v-for="(field, index) in filterFields" 
                  :key="field.key"
                  class="field-tag"
                >
                  <el-tag closable @close="removeField('filters', index)">
                    {{ field.label }}
                  </el-tag>
                </div>
                <div v-if="filterFields.length === 0" class="drop-placeholder">
                  拖拽字段到此处作为筛选条件
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 透视表结果 -->
    <el-card class="pivot-table-card">
      <template #header>
        <div class="table-header">
          <span>透视表结果</span>
          <div class="table-actions">
            <el-button size="small" @click="generatePivotTable">
              <el-icon><Refresh /></el-icon>
              生成透视表
            </el-button>
            <el-button size="small" @click="showChart = !showChart">
              <el-icon><TrendCharts /></el-icon>
              {{ showChart ? '隐藏图表' : '显示图表' }}
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 图表展示 -->
      <div v-if="showChart" class="chart-section">
        <div ref="pivotChart" style="height: 400px;"></div>
      </div>
      
      <!-- 透视表 -->
      <div class="pivot-table-wrapper">
        <el-table 
          :data="pivotTableData" 
          stripe 
          border
          style="width: 100%;"
          :span-method="arraySpanMethod"
        >
          <el-table-column 
            v-for="column in pivotTableColumns" 
            :key="column.prop"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :formatter="column.formatter"
          />
        </el-table>
      </div>
    </el-card>

    <!-- 配置对话框 -->
    <el-dialog v-model="showConfigDialog" title="透视表配置" width="600px">
      <el-form :model="configForm" label-width="100px">
        <el-form-item label="配置名称">
          <el-input v-model="configForm.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="数据源">
          <el-select v-model="configForm.dataSource" placeholder="选择数据源">
            <el-option label="销售数据" value="sales" />
            <el-option label="采购数据" value="purchase" />
            <el-option label="库存数据" value="inventory" />
            <el-option label="财务数据" value="finance" />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="configForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="显示小计">
          <el-switch v-model="configForm.showSubtotal" />
        </el-form-item>
        <el-form-item label="显示总计">
          <el-switch v-model="configForm.showGrandTotal" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showConfigDialog = false">取消</el-button>
          <el-button type="primary" @click="applyConfig">应用配置</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 保存配置对话框 -->
    <el-dialog v-model="showSaveDialog" title="保存配置" width="400px">
      <el-form :model="saveForm" label-width="80px">
        <el-form-item label="配置名称">
          <el-input v-model="saveForm.name" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="saveForm.description" type="textarea" placeholder="配置描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showSaveDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmSaveConfig">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  Setting, 
  DocumentAdd, 
  FolderOpened, 
  ArrowDown, 
  Printer, 
  Grid, 
  Refresh, 
  TrendCharts 
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const showConfigDialog = ref(false)
const showSaveDialog = ref(false)
const showChart = ref(true)
const pivotChart = ref()

// 可用字段
const availableFields = ref([
  { key: 'date', label: '日期', type: 'date' },
  { key: 'product', label: '产品', type: 'string' },
  { key: 'category', label: '类别', type: 'string' },
  { key: 'region', label: '地区', type: 'string' },
  { key: 'salesperson', label: '销售员', type: 'string' },
  { key: 'amount', label: '金额', type: 'number' },
  { key: 'quantity', label: '数量', type: 'number' },
  { key: 'profit', label: '利润', type: 'number' },
  { key: 'cost', label: '成本', type: 'number' }
])

// 透视表配置字段
const rowFields = ref([])
const columnFields = ref([])
const valueFields = ref([])
const filterFields = ref([])

// 透视表数据
const pivotTableData = ref([])
const pivotTableColumns = ref([])

// 配置表单
const configForm = reactive({
  name: '',
  dataSource: 'sales',
  dateRange: ['2024-01-01', '2024-12-31'],
  showSubtotal: true,
  showGrandTotal: true
})

// 保存表单
const saveForm = reactive({
  name: '',
  description: ''
})

// 拖拽相关方法
const handleDragStart = (event: DragEvent, field: any) => {
  event.dataTransfer?.setData('text/plain', JSON.stringify(field))
}

const handleDragOver = (event: DragEvent) => {
  event.preventDefault()
}

const handleDrop = (event: DragEvent, target: string) => {
  event.preventDefault()
  const fieldData = event.dataTransfer?.getData('text/plain')
  if (fieldData) {
    const field = JSON.parse(fieldData)
    
    // 为数值字段添加默认聚合函数
    if (target === 'values' && field.type === 'number') {
      field.aggregation = 'sum'
    }
    
    switch (target) {
      case 'rows':
        rowFields.value.push(field)
        break
      case 'columns':
        columnFields.value.push(field)
        break
      case 'values':
        valueFields.value.push(field)
        break
      case 'filters':
        filterFields.value.push(field)
        break
    }
    
    generatePivotTable()
  }
}

const removeField = (target: string, index: number) => {
  switch (target) {
    case 'rows':
      rowFields.value.splice(index, 1)
      break
    case 'columns':
      columnFields.value.splice(index, 1)
      break
    case 'values':
      valueFields.value.splice(index, 1)
      break
    case 'filters':
      filterFields.value.splice(index, 1)
      break
  }
  generatePivotTable()
}

const changeAggregation = (index: number, aggregation: string) => {
  valueFields.value[index].aggregation = aggregation
  generatePivotTable()
}

// 生成透视表
const generatePivotTable = () => {
  // 模拟透视表数据生成
  const mockData = [
    {
      '产品': '笔记本电脑',
      '地区': '华东',
      '2024-Q1': 150000,
      '2024-Q2': 180000,
      '2024-Q3': 200000,
      '2024-Q4': 220000,
      '总计': 750000
    },
    {
      '产品': '台式电脑',
      '地区': '华东',
      '2024-Q1': 120000,
      '2024-Q2': 140000,
      '2024-Q3': 160000,
      '2024-Q4': 180000,
      '总计': 600000
    },
    {
      '产品': '笔记本电脑',
      '地区': '华南',
      '2024-Q1': 100000,
      '2024-Q2': 120000,
      '2024-Q3': 140000,
      '2024-Q4': 160000,
      '总计': 520000
    },
    {
      '产品': '台式电脑',
      '地区': '华南',
      '2024-Q1': 80000,
      '2024-Q2': 90000,
      '2024-Q3': 100000,
      '2024-Q4': 110000,
      '总计': 380000
    }
  ]
  
  const columns = [
    { prop: '产品', label: '产品', width: 120 },
    { prop: '地区', label: '地区', width: 100 },
    { prop: '2024-Q1', label: '2024-Q1', width: 120, formatter: (row: any) => `¥${row['2024-Q1']?.toLocaleString()}` },
    { prop: '2024-Q2', label: '2024-Q2', width: 120, formatter: (row: any) => `¥${row['2024-Q2']?.toLocaleString()}` },
    { prop: '2024-Q3', label: '2024-Q3', width: 120, formatter: (row: any) => `¥${row['2024-Q3']?.toLocaleString()}` },
    { prop: '2024-Q4', label: '2024-Q4', width: 120, formatter: (row: any) => `¥${row['2024-Q4']?.toLocaleString()}` },
    { prop: '总计', label: '总计', width: 120, formatter: (row: any) => `¥${row['总计']?.toLocaleString()}` }
  ]
  
  pivotTableData.value = mockData
  pivotTableColumns.value = columns
  
  nextTick(() => {
    initChart()
  })
}

// 表格合并单元格
const arraySpanMethod = ({ row, column, rowIndex, columnIndex }: any) => {
  if (columnIndex === 0) {
    if (rowIndex % 2 === 0) {
      return {
        rowspan: 2,
        colspan: 1
      }
    } else {
      return {
        rowspan: 0,
        colspan: 0
      }
    }
  }
}

// 初始化图表
const initChart = () => {
  if (!pivotChart.value) return
  
  const chart = echarts.init(pivotChart.value)
  chart.setOption({
    title: {
      text: '透视表数据可视化',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['华东', '华南'],
      top: 30
    },
    xAxis: {
      type: 'category',
      data: ['2024-Q1', '2024-Q2', '2024-Q3', '2024-Q4']
    },
    yAxis: {
      type: 'value',
      name: '销售额(元)'
    },
    series: [
      {
        name: '华东',
        type: 'bar',
        data: [270000, 320000, 360000, 400000],
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '华南',
        type: 'bar',
        data: [180000, 210000, 240000, 270000],
        itemStyle: { color: '#67C23A' }
      }
    ]
  })
}

// 配置相关方法
const applyConfig = () => {
  showConfigDialog.value = false
  generatePivotTable()
  ElMessage.success('配置已应用')
}

const saveConfig = () => {
  showSaveDialog.value = true
}

const confirmSaveConfig = () => {
  showSaveDialog.value = false
  ElMessage.success(`配置"${saveForm.name}"已保存`)
  saveForm.name = ''
  saveForm.description = ''
}

const loadConfig = () => {
  ElMessage.success('配置加载功能开发中')
}

// 导出方法
const exportExcel = () => {
  ElMessage.success('Excel导出功能开发中')
}

const exportPDF = () => {
  ElMessage.success('PDF导出功能开发中')
}

const exportImage = () => {
  ElMessage.success('图片导出功能开发中')
}

const printReport = () => {
  window.print()
}

onMounted(() => {
  // 初始化默认透视表
  rowFields.value = [{ key: 'product', label: '产品', type: 'string' }]
  columnFields.value = [{ key: 'date', label: '日期', type: 'date' }]
  valueFields.value = [{ key: 'amount', label: '金额', type: 'number', aggregation: 'sum' }]
  
  generatePivotTable()
})
</script>

<style scoped>
.pivot-report {
  padding: 20px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.report-header h2 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  align-items: center;
}

.config-section {
  margin-bottom: 20px;
}

.field-list {
  max-height: 300px;
  overflow-y: auto;
}

.field-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  margin-bottom: 5px;
  background: #f5f7fa;
  border-radius: 4px;
  cursor: move;
  transition: all 0.3s;
}

.field-item:hover {
  background: #e4e7ed;
  transform: translateX(5px);
}

.field-item .el-icon {
  margin-right: 8px;
  color: #909399;
}

.drop-zone .drop-area {
  min-height: 80px;
  padding: 10px;
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
  background: #fafafa;
  transition: all 0.3s;
}

.drop-area:hover {
  border-color: #409EFF;
  background: #f0f9ff;
}

.drop-placeholder {
  color: #909399;
  text-align: center;
  line-height: 60px;
  font-size: 14px;
}

.field-tag {
  display: inline-block;
  margin: 5px;
}

.field-tag .el-tag {
  display: flex;
  align-items: center;
}

.pivot-table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.chart-section {
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 20px;
}

.pivot-table-wrapper {
  overflow-x: auto;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .report-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .header-actions {
    margin-top: 10px;
    flex-wrap: wrap;
  }
  
  .config-section .el-col {
    margin-bottom: 20px;
  }
}
</style>